package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.tanhua.api.CommentApi;
import com.itheima.tanhua.api.MovementApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.api.VideoApi;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.dto.UserFreezeDto;
import com.itheima.tanhua.enums.CommentType;
import com.itheima.tanhua.mongo.Comment;
import com.itheima.tanhua.mongo.Movement;
import com.itheima.tanhua.mongo.Video;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lff
 * @date 2022/4/5
 */
@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户数据翻页
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findUserInfoPage(Integer page, Integer pagesize) {
        //查询
        Page<UserInfo> pages = userInfoApi.findUserInfoByPage(page, pagesize);
        //处理结果
        List<UserInfo> records = pages.getRecords();
        for (UserInfo record : records) {
            if (redisTemplate.hasKey(Constants.USER_FREEZE + record.getId())) {
                //冻结
                record.setUserStatus("2");
            }
        }
        //填充pageresult
        PageResult pageResult = new PageResult(page, pagesize, pages.getTotal(), records);
        return pageResult;
    }

    /**
     * 根据用户id查询详情信息
     *
     * @param userId
     * @return
     */
    public UserInfo findUserInfoById(Long userId) {
        UserInfo result = userInfoApi.findById(userId);
        String key = Constants.USER_FREEZE + userId;
        if (redisTemplate.hasKey(key)) {
            result.setUserStatus("2");
        }
        return result;
    }


    /**
     * 查询指定用户的所有动态
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param status
     * @return
     */
    public PageResult findUserMovements(Integer page, Integer pagesize, Long uid, Integer status, String sortProp, String sortOrder) {
        //查询动态
        PageResult pr = movementApi.findMovementById(page, pagesize, uid, status, sortProp, sortOrder);
        List<Movement> movements = (List<Movement>) pr.getItems();
        if (CollUtil.isEmpty(movements)) {
            return new PageResult();
        }
        //抽取id
        List<Long> ids = CollUtil.getFieldValues(movements, "userId", Long.class);

        //查询并填充返回对象
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, null);
        List<MovementsVo> results = new ArrayList<>();
        for (Movement movement : movements) {
            UserInfo userInfo = userMap.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo init = MovementsVo.init(userInfo, movement);
                results.add(init);
            }
        }
        pr.setItems(results);
        return pr;
    }

    /**
     * 动态分页查询
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param sortProp
     * @param sortOrder
     * @return
     */
    public PageResult findUserVideos(Integer page, Integer pagesize, Long uid, String sortProp, String sortOrder) {
        PageResult pr = videoApi.findUserVideos(page, pagesize, uid, sortProp, sortOrder);
        List<Video> videos = (List<Video>) pr.getItems();
        if (CollUtil.isEmpty(videos)) {
            return new PageResult();
        }
        //抽取id
        List<Long> ids = CollUtil.getFieldValues(videos, "userId", Long.class);
        //查询mysql
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, null);
        List<VideoVo> results = new ArrayList<>();
        for (Video video : videos) {
            UserInfo userInfo = userMap.get(video.getUserId());
            if (userInfo != null) {
                VideoVo videoVo = VideoVo.init(userInfo, video);
                results.add(videoVo);
            }
        }
        pr.setItems(results);
        return pr;
    }

    /**
     * 获取动态的详情信息
     *
     * @param movementId
     */
    public MovementsVo findMovementsInfoById(String movementId) {
        Movement movement = movementApi.findOneById(movementId);
        if (movement == null) {
            return new MovementsVo();
        }
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        if (userInfo == null) {
            return null;
        }
        MovementsVo result = MovementsVo.init(userInfo, movement);
        return result;
    }

    /**
     * 根据动态id获取评论
     *
     * @param publishId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findMovementAllComments(String publishId, Integer page, Integer pagesize) {
        PageResult pr = commentApi.findCommentByPage(publishId, page, pagesize, CommentType.COMMENT);
        List<Comment> comments = (List<Comment>) pr.getItems();
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        //抽取id
        List<Long> ids = CollUtil.getFieldValues(comments, "userId", Long.class);
        //查询mysql
        Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, null);
        //填充
        List<CommentVo> results = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = userMap.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                results.add(commentVo);
            }
        }
        //填充
        pr.setItems(results);
        return pr;
    }

    /**
     * 冻结用户
     *
     * @param dto
     * @return
     */
    public Map freezeUser(UserFreezeDto dto) {
        String key = Constants.USER_FREEZE + dto.getUserId();
        String json = JSON.toJSONString(dto);
        //存到redis
        Integer times = 3650;
        //返回消息
        Map map = new HashMap();
        map.put("message", "账号已被封禁！");
        if (dto.getFreezingTime() == 1) {
            //三天
            times = 3;
        } else if (dto.getFreezingTime() == 1) {
            //七天
            times = 7;
        } else {
            //永久封禁
            redisTemplate.opsForValue().set(key, json);
            return map;
        }
        redisTemplate.opsForValue().set(key, json, Duration.ofMinutes(times));
        return map;
    }

    /**
     * 用户解冻
     *
     * @param params
     * @return
     */
    public Map unFreezeUser(Map params) {
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //移除缓存
        redisTemplate.delete(key);
        Map map = new HashMap();
        map.put("message", "账号已接触封禁！");
        return map;
    }
}
